package com.chengh.nami.common.utils;

import com.alibaba.fastjson2.JSON;
import com.chengh.nami.common.response.R;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletResponse;
import java.io.PrintWriter;

/**
 * @author chengh
 * 返回json
 */
@Slf4j
public class ResultUtils {

    /**
     * 使用response输出JSON
     * @author chengh
     */
    public static void responseJson(ServletResponse response, R<?> data) {
        PrintWriter out = null;
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");
            out = response.getWriter();
            out.println(JSON.toJSONString(data));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            if (out != null) {
                out.flush();
                out.close();
            }
        }
    }
}
